package com.jason.fontmetrics.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.jason.fontmetrics.R;

/**
 * @DESC: 给图片加一个类似阴影的效果该如何做呢？其实很简单，
 *        我们可以尝试从Bitmap中获取其Alpha通道，并在绘制Bitmap前先以该Alpha通道绘制一个模糊效果不就行了
 * @Author: Jason
 * @Date: 16/8/29
 * @Time: 22:30
 */

public class BlurMaskFilterView5 extends View {

    private Paint shadowPaint; // 画笔
    private Bitmap srcBitmap,shadowBitmap; // 位图和阴影位图
    private int x, y;// 位图绘制时左上角的起点坐标

    public BlurMaskFilterView5(Context context) {
        this(context, null);
    }

    public BlurMaskFilterView5(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 设置关闭硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        initPaint();

        initRes();

    }

    private void initRes() {

        // 获取位图
        srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);

        // 获取位图的Alpha通道
        shadowBitmap = srcBitmap.extractAlpha();
        // 计算位图绘制时左上角的坐标使其位于屏幕中心
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        x = width / 2 - srcBitmap.getWidth() / 2;
        y = height / 2 - srcBitmap.getHeight() / 2;


    }

    private void initPaint() {
        shadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        shadowPaint.setColor(Color.DKGRAY);
        shadowPaint.setMaskFilter(new BlurMaskFilter(40, BlurMaskFilter.Blur.NORMAL));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 先绘制阴影
        canvas.drawBitmap(shadowBitmap, x, y, shadowPaint);

        // 再绘制位图
        canvas.drawBitmap(srcBitmap, x, y, null);
    }
}
